package com.penghaisoft.microwms.base.web.auth.service.impl;

import com.penghaisoft.microwms.base.web.factory.dao.BaseFactoryMapper;
import com.penghaisoft.microwms.base.web.factory.dao.BaseFactoryUserMapper;
import com.penghaisoft.microwms.base.web.user.dao.BaseUserExportLogMapper;
import com.penghaisoft.microwms.base.web.user.dao.BaseUserLoginLogMapper;
import com.penghaisoft.microwms.base.web.user.dao.BaseUserMapper;
import com.penghaisoft.microwms.base.web.auth.service.IUserResroleService;
import com.penghaisoft.microwms.base.web.auth.service.IUserService;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.page.TurnPageInfo;
import com.penghaisoft.microwms.common.base.model.*;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Title: UserServiceImpl.java
 * @Description: 用户管理
 * @author zxcq0
 * @date 2017/2/28 16:18
 * @version V1.0
 */
@Service
public class UserServiceImpl extends BaseService<BaseUser> implements IUserService {


	@Autowired
	private BaseUserMapper baseUserMapper;

	@Autowired
	private IUserResroleService userResroleService;
	
	@Autowired
	private BaseUserLoginLogMapper baseUserLoginLogMapper;
	
	@Autowired
	private BaseUserExportLogMapper baseUserExportLogMapper;
	
	@Autowired
	private BaseFactoryMapper baseFactoryMapper;
	
	@Autowired
	private BaseFactoryUserMapper baseFactoryUserMapper;

	/**
	 * @Description: 根据id查询
	 * @author zxcq0
	 * @date 2017/2/28 16:24
	 * @param
	 * @return
	 */
	@Override
	public BaseUser queryById(String id) {
		BaseUser user = baseUserMapper.selectByPrimaryKey(id);
		return user;
	}

	/**
	 * @Description: 查询单条记录
	 * @author zxcq0
	 * @date 2017/3/3 9:10
	 * @param
	 * @return
	 */
	@Override
	public BaseUser queryOne(BaseUser user) {
		return baseUserMapper.selectOneByCondition(user);
	}

	/**
	 * @Description: 新增用户
	 * @author zxcq0
	 * @date 2017/3/1 10:18
	 * @param
	 * @return
	 */
	@Override
	public Resp add(BaseUser user) {
		//    重复性校验
		int count = baseUserMapper.checkAddUnique(user);
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		if (count != 0){
			resp.setCode(Constant.FAIL);
			resp.setMsg("base.auth.user.name.conflict");
		}else {
			//      真正插入
			String id = CommonUtils.getUUID();
			if (user.getPassword()==null||user.getPassword().equals("")){
				user.setPassword(CommonUtils.md5Hash(Constant.INIT_PWD));
			}else {
				user.setPassword(CommonUtils.md5Hash(user.getPassword()));
			}
			user.setUserId(id);
			user.setGmtCreate(new Date());
			baseUserMapper.insertSelective(user);
//			集团用户分配工厂
			if (Constant.USER_TYPE_GROUP.equals(user.getUserTypeCode())) {
				assignGroupUserFactory(user,"add");
			}
		}
		return resp;
	}
	
	/**
	 * @Description: 新增用户
	 * @author zxcq0
	 * @date 2017/3/1 10:18
	 * @param
	 * @return
	 */
	@Override
	public Resp addUser(BaseUser user) {
		//    重复性校验
		int count = baseUserMapper.checkAddUnique(user);
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		if (count != 0){
			resp.setCode(Constant.FAIL);
			resp.setMsg("用户名冲突！");
		}else {
			//      真正插入
			String id = CommonUtils.getUUID();
			if (user.getPassword()==null||user.getPassword().equals("")){
				user.setPassword(CommonUtils.md5Hash("123"));
			}else {
				user.setPassword(CommonUtils.md5Hash(user.getPassword()));
			}
			user.setUserId(id);
			user.setGmtCreate(new Date());
			baseUserMapper.insertSelective(user);
//			集团用户分配工厂
			if (Constant.USER_TYPE_GROUP.equals(user.getUserTypeCode())) {
				assignGroupUserFactory(user,"add");
			}
		}
		return resp;
	}
	

    /**
     * 分配集团用户的归属工厂
     * @param user
     */
    private void assignGroupUserFactory(BaseUser user,String type) {
//    	工厂组编码
		String factoryGroupCode = user.getFactoryGroupCode();
		if (factoryGroupCode!=null&&!"".equals(factoryGroupCode)) {
			String userId = user.getUserId();
			BaseFactory factoryCond = new BaseFactory();
			factoryCond.setGroupCode(factoryGroupCode);
			factoryCond.setActiveFlag("1");
//			工厂组下的工厂
			List<BaseFactory> factoryList = baseFactoryMapper.queryByAny(factoryCond);
//			要先删除该用户的归属工厂信息
			if ("upd".equals(type)) {
				baseFactoryUserMapper.deleteByUserId(userId);
			}
//			插入对象
			List<BaseFactoryUserKey> list = new ArrayList<>();
			for (BaseFactory baseFactory : factoryList) {
				BaseFactoryUserKey baseFactoryUserKey = new BaseFactoryUserKey();
				baseFactoryUserKey.setUserId(userId);
				baseFactoryUserKey.setFactoryId(baseFactory.getFactoryId());
				list.add(baseFactoryUserKey);
			}
			if (list.size() > 0) {
				baseFactoryUserMapper.insertFactoryUserBatch(list);
			}
			
		}
	}

	/**
	 * @Description: 更新用户
	 * @author zxcq0
	 * @date 2017/3/2 14:51
	 * @param
	 * @return
	 */
    @Transactional
	@Override
	public Resp update(BaseUser user) {
		//    重复性校验
		int count = baseUserMapper.checkUpdUnique(user);
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		if (count != 0){
			resp.setCode(Constant.FAIL);
			resp.setMsg("登录名重复！");
		}else {
			if (user.getPassword()!=null&&!user.getPassword().equals("")){
				user.setPassword(CommonUtils.md5Hash(user.getPassword()));
			}
			//      真正更新
			user.setGmtModified(new Date());
			baseUserMapper.updateByPrimaryKeySelective(user);
//			集团用户分配工厂
			if (Constant.USER_TYPE_GROUP.equals(user.getUserTypeCode())) {
				assignGroupUserFactory(user,"upd");
			}
		}
		return resp;
	}
    
    /* @Title: updateNoMd5 
     * @Description: 更新密码
     * @author luoteng
     * @date 2018年8月13日 下午2:27:24 
     */
    @Transactional
	@Override
	public Resp updateNoMd5(BaseUser user) {
		//    重复性校验
		int count = baseUserMapper.checkUpdUnique(user);
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		if (count != 0){
			resp.setCode(Constant.FAIL);
			resp.setMsg("登录名重复！");
		}else {
//			if (user.getPassword()!=null&&!user.getPassword().equals("")){
//				user.setPassword(CommonUtils.md5Hash(user.getPassword()));
//			}
			//      真正更新
			user.setGmtModified(new Date());
			baseUserMapper.updateByPrimaryKeySelective(user);
//			集团用户分配工厂
			if (Constant.USER_TYPE_GROUP.equals(user.getUserTypeCode())) {
				assignGroupUserFactory(user,"upd");
			}
		}
		return resp;
	}

	/**
	 * @Description: 根据id批量删除
	 * @author zxcq0
	 * @date 2017/3/2 15:21
	 * @param
	 * @return
	 */
	@Override
	@Transactional
	public Resp deleteBatch(List<String> userIds) {
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		int count = baseUserMapper.deleteByPrimaryKeys(userIds);
		if (count == 0){
			resp.setCode(Constant.FAIL);
			resp.setMsg("您删除的记录不存在！");
		}else {
			//      删除用户-角色关联关系
			userResroleService.deleteByUserIds(userIds);
		}
		return resp;
	}

	/**
	 * @Description:
	 * @author zxcq0
	 * @date 2017/3/1 16:38
	 * @param condition 查询条件
	 * @return
	 */
	@Override
	public List<BaseUser> queryList(BaseUser condition) {
		assemCondition(condition);
		List<BaseUser> users = baseUserMapper.selectListByCondition(condition);
		return users;
	}
	/**
	 * @Description: 返回翻页信息
	 * @author zxcq0
	 * @date 2017/3/2 16:44
	 * @param
	 * @return
	 */
	@Override
	public TurnPageInfo queryListPageInfo(BaseUser condition) {
		int totalCount = baseUserMapper.selectListByConditionCount(condition);
		TurnPageInfo pageInfo = getTurnPageInfo(totalCount,condition);
		return pageInfo;
	}

	/**
	 * @Description: 获取所有用户的id
	 * @author zxcq0
	 * @date 2017/3/24 10:08
	 * @param
	 * @return
	 */
	@Override
	public List<BaseUser> queryUserAll() {
		return baseUserMapper.queryUserAll();
	}

	/** 
	 * <p>Title: checkLogin</p> 
	 * <p>Description: 登录验证</p> 
	 * @Title: checkLogin 
	 * @Description: 登录验证
	 * @author zhangxu 
	 * @2017年6月5日:2017年6月5日:下午2:12:04
	 * @param @param condition
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public BaseUser checkLogin(BaseUser condition) {
		return baseUserMapper.checkLogin(condition);
	}

	/** 
	 * <p>Title: updateUserSysPwd</p> 
	 * <p>Description: </p> 
	 * @Title: updateUserSysPwd 
	 * @Description: 修改用户系统密码
	 * @author zhangxu 
	 * @2017年8月9日:2017年8月9日:下午3:20:55
	 * @param @param baseUser
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public Resp updateUserSysPwd(BaseUser baseUser) {
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		int i = baseUserMapper.updatePwdByUser(baseUser);
		if (i==0) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("base.auth.user.syspwd.error");
		}
		return resp;
	}

	/** 
	 * <p>Title: updateUserRfPwd</p> 
	 * <p>Description: </p> 
	 * @Title: updateUserRfPwd 
	 * @Description: 修改用户业务密码
	 * @author zhangxu 
	 * @2017年8月9日:2017年8月9日:下午3:34:53
	 * @param @param baseUser
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public Resp updateUserRfPwd(BaseUser baseUser) {
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		int i = baseUserMapper.updatePwdByUser(baseUser);
		if (i==0) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("base.auth.user.rfpwd.error");
		}
		return resp;
	}

	/** 
	 * <p>Title: queryHandLockUserList</p> 
	 * <p>Description:  查询手持用户锁定信息</p> 
	 * @Title: queryHandLockUserList 
	 * @Description:  查询手持用户锁定信息
	 * @author zhangxu 
	 * @2017年9月1日:2017年9月1日:下午1:30:24
	 * @param @param factoryCode
	 * @param @param loginNames
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public Pager<BaseUser> queryHandLockUserList(int page, int rows,String factoryCode,
			List<String> loginNames,BaseUser cond) {
		Pager<BaseUser> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		int size = baseUserMapper.queryHandLockUserCount(factoryCode,loginNames,cond);
		List<BaseUser> users = new ArrayList<>();
		if (size > 0) {
			users = baseUserMapper.queryHandLockUserList(factoryCode,loginNames,cond,(page-1)*rows,rows);
		}
		pager.setRecords(users);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * <p>Title: initPwd</p>
	 * <p>Description: </p>
	 * @Title: initPwd
	 * @Description: 密码初始化
	 * @author zhangxu
	 * @2017年9月26日:2017年9月26日:下午12:09:44
	 * @param @param cond
	 * @param @return
	 * @throws
	 * @version V0.1
	 */
	@Override
	public int initPwd(BaseUser cond) {
		cond.setLastPwdModifed(new Date());
		int count = baseUserMapper.updateByLoginName(cond);
		return count;
	}

	/**
	 * <p>Title: addLoginLog</p>
	 * <p>Description: </p>
	 * @Title: addLoginLog
	 * @Description: 记录登录日志
	 * @author zhangxu
	 * @2017年10月17日:2017年10月17日:下午2:17:31
	 * @param @param log
	 * @param @return
	 * @throws
	 * @version V0.1
	 */
	@Override
	public Resp addLoginLog(BaseUserLoginLog log) {
		Resp resp = new Resp();

		log.setActiveFlag("1");
		log.setGmtCreate(new Date());
		int i = baseUserLoginLogMapper.create(log);
		if (i > 0) {
			resp.setCode(Constant.SUCCESS);
		}else {
			resp.setCode(Constant.FAIL);
		}
		return resp;
	}

	/**
	 * <p>Title: queryLoginLogList</p>
	 * <p>Description: </p>
	 * @Title: queryLoginLogList
	 * @Description: 查询登录日志
	 * @author zhangxu
	 * @2017年10月17日:2017年10月17日:下午2:22:10
	 * @param @param page
	 * @param @param rows
	 * @param @param cond
	 * @param @return
	 * @throws
	 * @version V0.1
	 */
	@Override
	public Pager<BaseUserLoginLog> queryLoginLogList(int page, int rows, BaseUserLoginLog cond) {

		Pager<BaseUserLoginLog> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		long size = baseUserLoginLogMapper.queryCount(cond);
		List<BaseUserLoginLog> records = new ArrayList<BaseUserLoginLog>();
		if (size > 0) {
			records = baseUserLoginLogMapper.queryList(pager, cond);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * <p>Title: addExportLog</p>
	 * <p>Description: </p>
	 * @Title: addExportLog
	 * @Description: 记录导出日志
	 * @author zhangxu
	 * @2017年10月27日:2017年10月27日:下午5:04:21
	 * @param @param log
	 * @param @return
	 * @throws
	 * @version V0.1
	 */
	@Override
	public Resp addExportLog(BaseUserExportLog log) {
		Resp resp = new Resp();

		log.setActiveFlag("1");
		log.setGmtCreate(new Date());
		int i = baseUserExportLogMapper.create(log);
		if (i > 0) {
			resp.setCode(Constant.SUCCESS);
		}else {
			resp.setCode(Constant.FAIL);
		}
		return resp;
	}

	/**
	 * <p>Title: queryExportLogList</p>
	 * <p>Description: </p>
	 * @Title: queryExportLogList
	 * @Description: 查询导出日志
	 * @author zhangxu
	 * @2017年10月27日:2017年10月27日:下午5:04:56
	 * @param @param page
	 * @param @param rows
	 * @param @param cond
	 * @param @return
	 * @throws
	 * @version V0.1
	 */
	@Override
	public Pager<BaseUserExportLog> queryExportLogList(int page, int rows, BaseUserExportLog cond) {
		Pager<BaseUserExportLog> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		long size = baseUserExportLogMapper.queryCount(cond);
		List<BaseUserExportLog> records = new ArrayList<BaseUserExportLog>();
		if (size > 0) {
			records = baseUserExportLogMapper.queryList(pager, cond);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * 查询工厂下的所有用户
	 */
	@Override
	public List<BaseUser> queryUsersUnderFactory(String factoryCode) {
		List<BaseUser> users = baseUserMapper.queryUsersUnderFactory(factoryCode);
		return users;
	}

	/**
	 * cosmo-im添加查询工厂下的所有用户(带分页信息)
	 */
	@Override
	public List<BaseUser> queryUsersByFactory(int page, int rows,String factoryCode,BaseUser baseUser) {
		List<BaseUser> users = new ArrayList<>();
		users = baseUserMapper.queryUsersByFactory((page-1)*rows,rows,factoryCode,baseUser);
		return users;
	}

	@Override
	public List<BaseUser> queryListByLoginName(BaseUser condition) {
		// TODO Auto-generated method stub
		return baseUserMapper.queryByAny(condition);
	}
}
